package com.ibeeking.found.id.rest.service.impl;

import com.ibeeking.found.common.constants.IdRedisConstant;
import com.ibeeking.found.id.rest.service.IGenerateIdService;
import com.ibeeking.found.id.rest.service.IIdService;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.id.IdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName IdServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2020-11-13 16:02
 **/
@Service
public class IdServiceImpl implements IIdService {

    private static final Logger log = LoggerFactory.getLogger(IIdService.class);

    @Resource
    private IGenerateIdService generateIdServiceImpl;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public List<Object> selectIds(Integer count) {
        List<Object> result = new ArrayList<>();
        if (null == count) {
            count = 10000;
        }
        try {
            for (int i = 0; i < count; i++) {
                Object o = redisUtils.lLeftPop(IdRedisConstant.SNOWFLAKE_ID);
                if (null == o) {
                    generateIdServiceImpl.compensateGenerateId();
                } else {
                    result.add(o);
                }
            }
        } catch (Exception e) {
            log.error("获取id异常:{[]}", e);
        }
        if (Collections3.isEmpty(result)) {
            for (int i = 0; i < count; i++) {
                result.add(IdGenerator.getId());
            }
        }
        return result;
    }
}
